package com.li.controller;

import com.alibaba.fastjson.JSONObject;
import com.li.domain.Role;
import com.li.exception.NotFondException;
import com.li.service.RoleService;
import com.li.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @RequestMapping("/listRole")
    public List<Role> listRole(){
        return roleService.list();
    }

    @RequestMapping("/listPageRole")
    public JSONObject listPageRole(Role role,Integer page,Integer limit){
        List<Role> list = roleService.listRole(role,page,limit);
        Integer count = roleService.listRoleCount(role);
        return R.listPage(list,count);
    }

    @PostMapping("/saveOrUpdateRole")
    public JSONObject saveOrUpdateRole(Role role){
        if (role==null || role.getRoleName()==null){
            return R.getError(role);
        }
        if (role.getRoleId()==null || "".equals(role.getRoleId())){
            //添加
            try {
                roleService.addRole(role);
            }catch (Exception e){
                return R.getError(role);
            }
        }else{
            //修改
            try {
                roleService.updateRole(role);
            }catch (Exception e){
                return R.getError(role);
            }
        }
        return R.getSuccess();
    }

    @RequestMapping("/updateById")
    public JSONObject updateById(Role role){
        if (role.getRoleId()!=null){
            try {
                roleService.updateById(role);
            }catch (Exception e){
                return R.getError(role);
            }
        }
        return R.getSuccess();
    }

    @RequestMapping("/editRoleAndDeptIdAndMenuId")
    public Role editRoleAndDeptIdAndMenuId(Role role){
        return roleService.editRoleAndDeptIdAndMenuId(role);
    }

    @GetMapping("/editRole/{roleId}")
    public Role editRole(Integer roleId){
        return roleService.getById(roleId);
    }

    @GetMapping("/delRole/{roleId}")
    public void delRole(@PathVariable("roleId") Integer roleId){
        try {
            roleService.delRole(roleId);
        }catch (Exception e){
            throw new NotFondException("角色删除失败");
        }
    }

}
